package cuit.cx.groupcomment.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cuit.cx.groupcomment.dto.GroupDetail;
import cuit.cx.groupcomment.dto.GroupDto;
import cuit.cx.groupcomment.model.Userinfo;
import cuit.cx.groupcomment.service.GrouponService;
import cuit.cx.groupcomment.service.UserinfoService;
import cuit.cx.groupcomment.util.Constant;
import cuit.cx.groupcomment.util.ContextLoaderListener;
import cuit.cx.groupcomment.util.GroupComment;
import cuit.cx.groupcomment.util.JsonHelper;

public class MainServlet extends HttpServlet 
{
	private Logger log = Logger.getLogger(MainServlet.class);
	UserinfoService userinfoService;
	GrouponService grouponService;
	
	

	@Override    
	    public void init() throws ServletException {            
	        super .init();    
	                    
	        userinfoService = (UserinfoService) ContextLoaderListener.instance.getContextLoader().getCurrentWebApplicationContext().getBean("userinfoService");
	        grouponService = (GrouponService) ContextLoaderListener.instance.getContextLoader().getCurrentWebApplicationContext().getBean("grouponService");
	         /*ServletContext servletContext = this .getServletContext();              
	         WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);    
	         userinfoService = (UserinfoService) ctx.getBean("userinfoService");*/
	         log.error("init MainServlet "+userinfoService+"_"+grouponService);
   
	     }  
	
	public UserinfoService getUserinfoService() {
		return userinfoService;
	}


	public void setUserinfoService(UserinfoService userinfoService)
	{
		this.userinfoService = userinfoService;
		log.info("Injection seccess!");
	}

	public GrouponService getGrouponService()
	{
		return grouponService;
	}

	public void setGrouponService(GrouponService grouponService)
	{
		this.grouponService = grouponService;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
	{
		doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
    {
		/*
		 * ServletContext sc = getServletContext(); WebApplicationContext wc =
		 * WebApplicationContextUtils.getWebApplicationContext(sc);
		 * userinfoService = (UserinfoService) wc.getBean("userinfoService");
		 */

		System.out.println(userinfoService);

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		String result = null;
		log.info("action=" + action);

		if (action == null) 
		{
			return;
		}
		if (action.equals(Constant.ACTION_LOGIN))
		{			
			String userEmail = request.getParameter("userEmail");
			String userPassword = request.getParameter("userPassword");
			Userinfo userinfo = userinfoService.login(userEmail, userPassword);
			result = JsonHelper.getRegisterUserinfoResult(userinfo);	
		}
		else if (action.equals(Constant.ACTION_REGISTER)) 
		{
			String email = request.getParameter("email");
			String name = request.getParameter("name");
			String phoneNumber = request.getParameter("phoneNumber");
			String password = request.getParameter("password");
			String power = request.getParameter("power");
			Userinfo userinfo = userinfoService.register(email, name, phoneNumber, password, power);
			int res = Constant.ACK_FAIL;
			if (userinfo != null)
			{
				res = Constant.ACK_OK;
			}
		
			result = JsonHelper.getUserinfoResult(res, null);

		} 
		else if (action.equals(Constant.ACTION_ADD_GROUPON)) 
		{
			/* businissID
			 * shopName
			 * name
			 * introdution
			 * prompt
			 * nowPrice
			 * oldPrice
			 * startTime
			 * endTime
			 * shopIntro
			 * groupType
			 * orderCount
			 */

		} 
		else if (action.equals(Constant.ACTION_ADD_ORDERINFO)) 
		{
			/**
			 * userID
			 * grouponID
			 * orderCount
			 */
			

		} 
		else if (action.equals(Constant.ACTION_ADD_COMMENT))
		{
			/**
			 *serialID
			 *commentIntro
			 *serviceScore
			 *envirScore
			 *expenScore
			 * 
			 */

		}
		else if (action.equals(Constant.ACTION_QUERY_GROUPTODAY_ALL)) 
		{
			
			/**
			 * endTime 
			 */
			
			String time = request.getParameter("nowTime");
			List<GroupDto> list = grouponService.findCurrentGroup(time);
			result = JsonHelper.getGroupListJson(list);
			
			

		}
		else if (action.equals(Constant.ACTION_QUERY_GROUPBEGONE_ALL)) 
		{
			
			/**
			 * endTime
			 */
			
			String time = request.getParameter("nowTime");
			List<GroupDto> list = grouponService.findCurrentGroup(time);
			result = JsonHelper.getGroupListJson(list);

		} 
		else if (action.equals(Constant.ACTION_QUERY_GROUP_SINGLE)) 
		{
			
			/**
			 *  id
			 */
			String id = request.getParameter("id");
			GroupDetail dto = grouponService.findGrouponById(id);
		

		} 
		else if (action.equals(Constant.ACTION_CHANGE_USERINFO)) 
		{
			
			String id = request.getParameter("id");
			String email = request.getParameter("email");
			String name = request.getParameter("name");
			String phoneNumber = request.getParameter("phoneNumber");
			String password = request.getParameter("password");
			Userinfo userinfo = userinfoService.changeUserinfo(id, email, name, phoneNumber, password);
			result = JsonHelper.getRegisterUserinfoResult(userinfo);
		}

		else if (action.equals("getlist")) {
			List<Userinfo> list = userinfoService.findUserinfos();
			if (list != null && !list.isEmpty()) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("list", list);
				jsonObject.put("results", list.size());
				result = jsonObject.toString();
			}
		} else if (action.equals("adduser")) {
			System.out.println(request.getParameter("name"));
			result = "{\"success\":true}";

		} else {
			result = "";
		}
		
		System.out.println("Result:"+result);

		out.write(result);
		out.flush();
		out.close();
	}

}
